const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

/**
 * 构建时替换用户参数的脚本
 */
function buildWithUser() {
  const buildUser = process.env.BUILD_USER

  if (!buildUser) {
    console.log('⚠️  未指定构建用户，将跳过用户验证')
    // 不做任何替换，直接构建
    execSync('tsc', { stdio: 'inherit' })
    return
  }

  console.log(`🔐 构建用户: ${buildUser}`)

  // 读取原始文件
  const decryptFilePath = path.join(
    __dirname,
    '../src/modules/decrypt/decrypt.utils.ts'
  )
  let content = fs.readFileSync(decryptFilePath, 'utf-8')

  // 创建备份
  const backupPath = decryptFilePath + '.backup'
  fs.writeFileSync(backupPath, content, 'utf-8')

  try {
    // 替换占位符
    const modifiedContent = content.replace(
      /\/\* BUILD_USER_PLACEHOLDER \*\//g,
      `// 验证构建时指定的用户
        const expectedUser = '${buildUser}';
        if (jsonContent.user !== expectedUser) {
            throw new Error(\`许可证用户不匹配\`);
        }`
    )

    // 写入修改后的内容
    fs.writeFileSync(decryptFilePath, modifiedContent, 'utf-8')

    // 执行构建
    execSync('tsc', { stdio: 'inherit' })

    console.log('✅ 构建完成')
  } finally {
    // 恢复原始文件
    fs.writeFileSync(decryptFilePath, content, 'utf-8')
    fs.unlinkSync(backupPath)
    console.log('🔄 已恢复原始文件')
  }
}

// 执行构建
buildWithUser()
